package com.cn.wanxi.jwt.controller;


import com.cn.wanxi.jwt.domain.User;
import com.cn.wanxi.jwt.result.CommonResult;
import com.cn.wanxi.jwt.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 后台用户表 前端控制器
 * </p>
 *
 * @author 吉酱
 * @since 2022-09-27
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Value("${jwt.tokenHead}")
    String tokenHead;

    @Autowired
    private IUserService userService;


    /**
     * @MethodName add
     * @Description 添加用户
     * @Param [user]
     * @Return com.cn.wanxi.springsecurity.domain.User
     **/
    @PreAuthorize("hasAuthority('wx:user:create')")
    @PostMapping
    public String saveUser(User user) {

        int affectedRow = userService.addUser(user);
        return affectedRow > 0 ? "保存用户信息<font color=\"green\">成功！</font>" :
                "保存用户信息<font color=\"red\">失败！</font>";
    }


    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('wx:user:delete')")
    public String removeUser(@PathVariable("id") Integer id) {

        int affectedRow = userService.deleteUserById(id);
        return affectedRow > 0 ? "移除用户信息<font color=\"green\">成功！</font>" :
                "移除用户信息<font color=\"red\">失败！</font>";
    }


    @PutMapping
    @PreAuthorize("hasAuthority('wx:user:update')")
    public String modifyUser(User user) {


        int affectedRow = userService.updateUser(user);
        return affectedRow > 0 ? "修改用户信息<font color=\"green\">成功！</font>" :
                "修改用户信息<font color=\"red\">失败！</font>";
    }


    /**
     * @MethodName findById
     * @Description 根据id查询用户
     * @Param [id]
     * @Return com.cn.wanxi.springsecurity.domain.User
     **/
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('wx:user:read')")// 授权：有 wx:user:read 权限才能做该操作
    public User findById(@PathVariable("id") Integer id) {
        return userService.getUserById(id);
    }


    @GetMapping
    @PreAuthorize("hasAuthority('wx:user:read')")// 授权：有 wx:user:read 权限才能做该操作
    public List<User> findAll(User user) {

        return userService.getAllUser(user);

    }


    @GetMapping("/detail")
//    @PreAuthorize("hasAuthority('wx:user:read')")
    public Map<String, Object> findCurrentUserDetails(/*HttpSession session*/) {

         /*Spring Security会将SecurityContextHolder里的数据保存到Session中，
         SecurityContextHolder 存储的是SecurityContext对象
         SecurityContext 存储的是Authentication对象*/
        //这里是从线程里面获取的
        Map<String, Object> infoMap = new HashMap<>();

        //这里是从线程里面获取的
        //获取上下文对象
        SecurityContext securityContext = SecurityContextHolder.getContext();
        infoMap.put("SecurityContext", securityContext);

        //获取认证对象
        Authentication authentication = securityContext.getAuthentication();
        infoMap.put("authentication", authentication);


        //获取principal
        Object principal = authentication == null ? null : authentication.getPrincipal();
        infoMap.put("principal", principal);

        return infoMap;

    }


    @GetMapping("/test")
//    @PreAuthorize("hasAuthority('wx:user:read')")
    public Map<String, Object> test() {


        Map<String, Object> infoMap = new HashMap<>();


        //这里是从线程里面获取的
        //获取上下文对象
        SecurityContext securityContext = SecurityContextHolder.getContext();
        infoMap.put("SecurityContext", securityContext);

        //获取认证对象
        Authentication authentication = securityContext.getAuthentication();
        infoMap.put("authentication", authentication);


        //获取principal
        Object principal = authentication == null ? null : authentication.getPrincipal();
        infoMap.put("principal", principal);


        return infoMap;
    }


    //region
    @PostMapping("/login")
    public CommonResult login(@RequestBody User user) {

        HashMap<String, String> data = new HashMap<>();
        String token = null;
        try {
            token = userService.loginBySecurity(user);
//            token = userService.login(user);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.validateFailed("用户名或密码错误");
        }
        if (StringUtils.isEmpty(token)) {
            return CommonResult.validateFailed("用户名或密码错误");
        }
        data.put("tokenHead", tokenHead);
        data.put("access_token", token);
        // localStorage.setItem("Authorization","Bearer sdsdfdfds")
        // $ajax{data:{},type:"",header:{"Authorization":"Bearer sdsdfdfds"}}
        return CommonResult.success(data);
    }
    //endregion


}

